package com.qgzj.util;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class ApplicationUtil {

    // 批量操作传参数分隔符
    public static String SEPRATOR_CHAR = ",";

    public final static Integer SEQ_MAX = 99;

    public final static Integer SEQ_MIN = 11;

    public static Integer seq_result = 10;

    public static final int PWD_SALTY_LEN = 6;

    // 分页默认值
    public static final Integer PAGESIZE_DEF_VAL = 10;

    public static final Integer PAGE_DEF_VAL = 1;

    public static final String NUMBERCHAR = "0123456789";

    /**
     * 登录用户redis key
     */
    public static final String QGZJ_LOGIN_USER_REDIS_KEY = "qgzj_login_user_id_";


    public static final String QGZJ_WECHAT_SESSION_KEY = "qgzj_wechat_session_key";

    /**
     * 登录用户cookie key
     */
    public static final String QGZJ_LOGIN_USER_COOKIE_KEY = "qgzj_login_user_key_";

    /**
     * 验证码redis key
     */
    public static final String QGZJ_VERIFY_CODE_REDIS_KEY = "qgzj_verify_code_id_";

    /**
     * 验证码cookie key
     */
    public static final String QGZJ_VERIFY_CODE_COOKIE_KEY = "qgzj_verify_code_key_";

    /**
     * 剩余分享app次数
     */
    public static final String QGZJ_SHARE_APP_TIMES = "qgzj_share_app_times_";

    /**
     * 剩余分享新闻次数
     */
    public static final String QGZJ_SHARE_NEWS_TIMES = "qgzj_share_news_times_";

    /**
     * sso登录userNo cookie key
     */
    public static final String QGZJ_SSO_LOGIN_USERNO_COOKIE_KEY = "qgzj_sso_login_user_no_";

    /**
     * sso登录用户redis key
     */
    public static final String QGZJ_SSO_LOGIN_USER_REDIS_KEY = "qgzj_sso_login_user_";

    /**
     * sso图形验证码 cookie key
     */
    public static final String QGZJ_SSO_VERIFY_CODE_COOKIE_KEY = "qgzj_sso_verify_code_no_";

    /**
     * sso图形验证码 redis key
     */
    public static final String QGZJ_SSO_VERIFY_CODE_REDIS_KEY = "qgzj_sso_verify_code_";
    /**
     * sso手机验证码redis key
     */
    public static final String QGZJ_SSO_SMS_CODE_REDIS_KEY = "qgzj_sso_sms_code_";
    /**
     * sso邮件验证码redis key
     */
    public static final String QGZJ_SSO_EMAIL_CODE_REDIS_KEY = "qgzj_sso_email_code_";
    /**
     * 系统使用寿命（天数）redis key
     */
    public static final String QGZJ_SERVICE_LIFE_REDIS_KEY = "qgzj_sys_service_life";
    /**
     * pc h5图形验证码 cookie key
     */
    public static final String QGZJ_WEB_VERIFY_CODE_COOKIE_KEY = "qgzj_web_verify_code_cookie_key_";
    /**
     * pc h5图形验证码 redis key
     */
    public static final String QGZJ_WEB_VERIFY_CODE_REDIS_KEY = "qgzj_web_verify_code_redis_key_";

    /**
     * 新闻已读次数count key
     */
    public static final String QGZJ_WEB_NEWS_READ_COUNT_KEY = "qgzj_web_news_read_count_key_";

    /**
     * 图形验证码 key
     *
     * 微信运动会签到
     */
    public static final String QGZJ_WEB_IMAGE_CAPTCHA_REDIS_KEY = "qgzj_web_signed_image_captcha_redis_key_";

    /**
     * 帮扶活动是否在进行
     */
    public static final String QGZJ_BANG_FU_ACTIVITY_OVER = "qgzj_bang_fu_activity_over_";

    /**
     * 字典列表缓存key
     */
    public static final String QGZJ_ACTIVITY_DICTIONARY_KEY = "qgzj_activity_dictionary_key_";

    /**
     * 部门编号缓存key
     */
    public static final String QGZJ_DEPT_NO_KEY = "qgzj_dept_no_key_";


    /**
     * 初始化分享新闻次数
     */
    public static final int SHARE_NEWS_TIMES = 5;

    /**
     * 初始化分享app次数
     */
    public static final int SHARE_APP_TIMES = 3;

    /**
     * 登录失效时间 30分钟
     */
    public static int minutes = 30 * 1000;
    
    /**
     * 所属工会失效时间 30分钟
     */
    public static int UNION_MINUTES = 30;

    /**
     * 会员系统 默认密码
     */
    public static final String DEFAULT_SECRET_CODE = "1234567890";

    /**
     * 生产随机码(含大小写和数字)
     * 
     * @return
     */
    public static String genSalty(int length) {
        char[] passwordLit = new char[62];
        char fword = 'A';
        char mword = 'a';
        char bword = '0';
        for (int i = 0; i < 62; i++) {
            if (i < 26) {
                // 大写字母
                passwordLit[i] = fword;
                fword++;
            } else if (i < 52) {
                // 小写字母
                passwordLit[i] = mword;
                mword++;
            } else {
                // 数字
                passwordLit[i] = bword;
                bword++;
            }
        }

        Random rr = new Random();
        char[] pw = new char[length];
        for (int i = 0; i < pw.length; i++) {
            int num = rr.nextInt(62);
            pw[i] = passwordLit[num];
        }
        return String.valueOf(pw);
    }

    /**
     * 获取IP
     */
    public static String getRemortIP(HttpServletRequest request) {
        String ipAddress = null;
        // ipAddress = request.getRemoteAddr();
        ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1")) {
                // 根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }

        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
            // = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    /**
     * 获取两位数序列
     */
    public static int genSeq() {
        seq_result++;
        if (seq_result > SEQ_MAX) {
            seq_result = SEQ_MIN;
        }
        return seq_result;
    }

    /**
     * 生成19位的编号
     * @return
     */
    public static String genNo(){
        return new StringBuilder(genSeq(new Date())).toString();
    }

    /**
     * 日期到毫秒+两位数序列
     */
    public static String genSeq(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        StringBuffer stringBuffer = new StringBuffer(sdf.format(date));
        stringBuffer.append(genSeq());
        return stringBuffer.toString();
    }

    /**
     * 生成编号，年月日时分秒+6位随机数
     *
     * @return
     */
    public static String getCommonNo() {
        return new StringBuffer(DateUtil.getLongDateString(new Date())).append(ApplicationUtil.genRandomCode(6)).toString();
    }
    
    /**
     * 流水编号
     */
    public static String getSerialNo(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat sdfm = new SimpleDateFormat("HHmmss");
        StringBuffer stringBuffer = new StringBuffer(sdf.format(date));
        stringBuffer.append("-").append(sdfm.format(date));
        return stringBuffer.toString();
    }
    
    /**
     * 菜单编号
     */
    public static String getMenuNo(Date date) {
    	StringBuffer stringBuffer = new StringBuffer();
        SimpleDateFormat sdfm = new SimpleDateFormat("mmss");
        stringBuffer.append(genRandomCode(2)).append(sdfm.format(date));
        return stringBuffer.toString();
    }
    
    /**
     * 六位随机数
     */
    public static String genRandomCode(int length) {
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(NUMBERCHAR.charAt(random.nextInt(NUMBERCHAR.length())));
        }
        return sb.toString();
    }

    /**
     * URL解码
     */
    public static String urlDecoder(String s, String charcoding) {
        if (s == null) {
            return null;
        }
        try {
            return URLDecoder.decode(s, charcoding);
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * URL编码
     */
    public static String urlEncoder(String s, String charcoding) {
        if (s == null) {
            return null;
        }
        try {
            return URLEncoder.encode(s, charcoding);
        } catch (Exception e) {
        }
        return null;
    }



    /**
     * 补位
     *
     * @param index
     * @return
     */
    private static String dealIndex(Integer index) {
        // 设置最多补位为000个
        index = index + 1;
        String indexStr = index.toString();
        if (indexStr.length() == 1){
            return "00" + indexStr;
        }else if(indexStr.length() == 2){
            return "0" + indexStr;
        }else{
            return indexStr;
        }
    }


    /**
     * 金秋助学--助学申请--会员子女编号
     * @return
     */
    public static String genGrantMemberChildNo(String memberNo){
        return new StringBuilder(memberNo).append(genRandomCode(2)).toString();
    }

}
